<script lang="ts" setup>
import { onMounted, ref, watch } from 'vue';
import type { TreeData, TreeInstance, TreeNodeData } from 'element-plus';
import { fetchGetDeptTree } from '@/service/api';

defineOptions({ name: 'DeptTree' });

interface Props {
  showExtra?: boolean;
  refresh?: number;
}

const props = defineProps<Props>();

interface Emits {
  (event: 'nodeClick', data: TreeNodeData): void;
}

const emit = defineEmits<Emits>();

const treeRef = ref<TreeInstance | null>(null);
const treeData = ref<TreeData>([]);
const filterText = ref<string>('');

onMounted(async () => {
  await getDeptTree();
});

async function getDeptTree() {
  const { data, error } = await fetchGetDeptTree();
  if (!error && data) {
    if (props.showExtra && data.children && data.children.length > 0) {
      data.children = [
        {
          key: 'ALONE',
          value: '-1',
          label: '独立用户',
          children: [],
          data: null
        }
      ].concat(data.children);
    }
    treeData.value = [data];
  }
}

const filterNode = (value: string, data: TreeNodeData) => {
  if (!value) return true;
  return data.label.includes(value);
};

watch(filterText, text => {
  treeRef.value?.filter(text);
});

watch(
  () => props.refresh,
  () => {
    // getDeptTree();
  }
);
</script>

<template>
  <div>
    <ElInput v-model="filterText" placeholder="请输入部门名称" class="mb-2" clearable />
    <ElTree
      ref="treeRef"
      :data="treeData"
      node-key="key"
      :filter-node-method="filterNode"
      :default-expanded-keys="['ROOT']"
      :expand-on-click-node="false"
      @node-click="emit('nodeClick', $event)"
    />
  </div>
</template>

<style scoped lang="scss"></style>
